import img_ocr
import mouser_opt
import pyautogui as pag
import cv2
import numpy as np
import sqlite3
import time

#需要获取的屏幕尺寸
opt_dstwin_xy=None
opt_dstwin_wh=None
def setwinPos(x, y, w, h):
    global opt_dstwin_xy
    global opt_dstwin_wh
    opt_dstwin_xy=(x,y)
    opt_dstwin_wh=(w,h)

def img_detect_save_topic(data):
    conn = sqlite3.connect('example.db')
    cur = conn.cursor()

    cur.execute("INSERT INTO questionTab (topic, answer) VALUES (?, ?)", (data[0], ""))
    
    #cur.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
    #cur.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("John", "john@example.com"))
    #cur.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Jane", "jane@example.com"))
    conn.commit()
    cur.close()
    conn.close()    
def img_detect_find_result(topic):
    conn = sqlite3.connect('example.db')
    cur = conn.cursor()

    results =cur.execute("select * from questionTab where topic='{}'".format(topic))
    allrow = results.fetchall()
 
    cur.close()
    conn.close()    

    if len(allrow)>0:
        return allrow[0]
    return None
def get_select_region_img():
    global opt_dstwin_xy
    global opt_dstwin_wh
    im = pag.screenshot(region=(opt_dstwin_xy[0],opt_dstwin_xy[1], opt_dstwin_wh[0] ,opt_dstwin_wh[1]))
    # 保存图片
    img_result = cv2.cvtColor(np.array(im),cv2.COLOR_RGB2BGR)
    return img_result

def img_detect_main():
    #img = cv2.imread(r'ocr-test.png')
    #img = cv2.imread(r'result.png')
    #获取题目
    find_img = cv2.imread(r'test.png')
    #find_img = get_select_region_img()
    cv2.imshow("img",find_img)
    # 获取原始图片的宽度和高度
    height, width = find_img.shape[:2]
    # 将图片缩放到1.5倍大小
    find_img = cv2.resize(find_img, (int(2*width), int(2*height)), interpolation = cv2.INTER_CUBIC)
    cv2.imshow("big",find_img)
    cv2.waitKey()
    data = img_ocr.recoText(find_img)
    
    print("开始",data)
    #mysql查找答案
    find_topic = img_detect_find_result(data[0])
    if find_topic != None:
        print("find_topic",find_topic)
        #有答案，做题完成
    else:
        #没有答案，随机做题
        mouser_opt.select_btn_ok()
        mouser_opt.select_btn_commit()
        time.sleep(2)
        
         #保存答案
        #img_result = cv2.imread(r'result.png')
        data = img_ocr.recoText(get_select_region_img())
        print("保存结果",data)
        strResult = img_ocr.find_question_result(data)
        print("保存结果",strResult)
        img_detect_save_topic(strResult)
        pass
   

if __name__ == '__main__':
    img_detect_main()

